﻿using Daq.Tools.HttpClientHelper;
using DaqCollectionClient.Model;
using FileRead;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text.RegularExpressions;
using System.Windows;
using System.Windows.Documents;
using System.Windows.Markup;
using Tools;

namespace DaqCollectionClient.Core
{
    /// <summary>
    /// 数据上传
    /// </summary>
    internal class DataUploading
    {
        /// <summary>
        /// 输出消息
        /// </summary>
        private Action<string> OutPutLogEvent = null;

        public DataUploading(string fileFullPath, string serverApi, Action<string> outPutLogEvent)
        {
            OutPutLogEvent = outPutLogEvent;

            var resultData = new List<DataUploadingDTO>();
            try
            {
                resultData = AnalysisFile(fileFullPath);
                OutPutLogEvent($"数据解析成功，共{resultData.Count}条数据");
            }
            catch (Exception ex)
            {
                OutPutLogEvent($"数据解析失败：{ex}");
            }
            try
            {
                Uploading(serverApi, resultData);
            }
            catch (Exception ex)
            {
                OutPutLogEvent($"数据上传失败：{ex}");
            }
        }

        /// <summary>
        /// 解析文件
        /// </summary>
        /// <param name="filePath"></param>
        public List<DataUploadingDTO> AnalysisFile(string fileFullPath)
        {
            var result = new List<DataUploadingDTO>();

            var extension = System.IO.Path.GetExtension(fileFullPath).ToUpper();
            if (extension.Contains(".DOC"))
            {
                string data = WordHelp.ReadAllText(fileFullPath);

                var content = data.Split(new string[] { "方法标题" }, StringSplitOptions.RemoveEmptyEntries);
                foreach (var item in content)
                {
                    var barCode = item.FindByLineFirst("谱图标题:").Trim();
                    var upLoadTime = ParseDateTime(item.FindByLineFirst("光谱日期:", "").Trim());

                    var contents = item.Find("单位").Split(new string[] { "\r\n", "\r", "\n" }, StringSplitOptions.RemoveEmptyEntries);
                    foreach (var row in contents)
                    {
                        if (string.IsNullOrWhiteSpace(row))
                            continue;

                        var rowContent = row.Split(new string[] { " ", "\t" }, StringSplitOptions.RemoveEmptyEntries);
                        if (rowContent.Length > 3)
                        {
                            var groupData = rowContent[1] ?? string.Empty;
                            var dataValue = rowContent[2] ?? string.Empty;
                            var unit = rowContent[3] ?? string.Empty;
                            var resultValue = "OK";

                            result.Add(new DataUploadingDTO()
                            {
                                BarCode = barCode,
                                UpLoadTime = upLoadTime,
                                GroupData = groupData,
                                DataValue = dataValue,
                                Unit = unit,
                                Result = resultValue
                            });
                        }
                    }
                }
            }
            return result;

            DateTime ParseDateTime(string dateString)
            {
                string[] parts = dateString.Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries);

                string month = parts[1].Substring(0, parts[1].Length - 1);

                return new DateTime(int.Parse(parts[4]), int.Parse(month), int.Parse(parts[2]),
                                    int.Parse(parts[3].Split(':')[0]), int.Parse(parts[3].Split(':')[1]),
                                    int.Parse(parts[3].Split(':')[2]));
            }
        }

        /// <summary>
        /// 上传
        /// </summary>
        public void Uploading(string serverApi, List<DataUploadingDTO> datas)
        {
            if (!datas.Any())
                return;

            var url = $"{serverApi}/API/Record/LineOxyCheck";

            List<string> msgs = new List<string>();
            foreach (var item in datas)
            {
                var result = HttpHelp.PostJsonAsync<Response>(url, param => param.AddJson(item)).Result;
                if (!result.State.Contains("OK"))
                {
                    msgs.Add(result.Message);
                }
            }
            if (msgs.Any())
            {
                OutPutLogEvent($"一共：{datas.Count}条数据，发送失败：{msgs.Count}条，失败消息：{string.Join("、", msgs)}");
            }
            else
            {
                OutPutLogEvent("数据全部发送成功");
            }
        }

        public class Response
        {
            public string State { get; set; } //OK/Error

            public string Message { get; set; }
        }
    }
}